var ul = document.querySelector('ul')
function textRender() {
    var text = ''
    data.forEach(function (item) {
        var str = `<li><input type="checkbox"${item.checked ? 'checked' : ''}><p>${item.name}</p><a href="javascript:;" id="love" >收藏</a><a href="javascript:;" id="del">删除</a></li>`
        text += str
    })
    ul.innerHTML = text;

    //改变全选的值
    all.children[0].checked = true
    if (data.length) {
        data.forEach(function (item) {
            if (!item.checked) {
                all.children[0].checked = false
            }
        })
    } else {
        all.children[0].checked = false
    }




    liRender()
    delRender()
    loveRender()
    console.log(data);
}



function bottomRender() {
    //提交
    var sub = document.querySelector('#submit');
    var subText = document.querySelector('#subtext');

    sub.addEventListener('click', function () {
        if (subText.value.trim()) {
            data.push({ name: subText.value, checked: false })
            textRender()
        }
        subText.value = ''
    })

    //全选 | 全不选
    var all = document.querySelector("#all")
    var none = document.querySelector("#none")
    var delAll = document.querySelector("#delAll")
    all.children[0].checked = false;//这一句是为了初始化
    all.onclick = () => {
        all.children[0].checked = !all.children[0].checked;
        data.forEach((item) => {
            item.checked = all.children[0].checked;
        })
        textRender()
    }
    all.children[0].onclick = () => {
        all.children[0].checked = !all.children[0].checked;
    }
    none.onclick = () => {
        data.forEach((item) => {
            item.checked = false;
        })
        textRender()
    }
    delAll.onclick = () => {
        data = data.filter(item => !item.checked)
        textRender()
    }
}

//给li绑定选定
function liRender() {
    var checkLi = document.querySelectorAll('li input')
    checkLi.forEach((item, index) => {
        item.onclick = () => {
            data[index].checked = item.checked;
            textRender()
        }
    })
}

//给收藏绑定收藏
function loveRender() {
    var loveLi = document.querySelectorAll('li #love')
    loveLi.forEach((item, index) => {
        item.love = false;
        item.onclick = () => {
            if (item.love) {
                item.innerHTML = '收藏'
            } else {
                item.innerHTML = '取消收藏'
            }
            item.love = !item.love
        }
    })
}

//给所有a绑定删除
function delRender() {
    var delLi = document.querySelectorAll('li #del')
    delLi.forEach((item, index) => {
        item.onclick = () => {
            data.splice(index, 1)
            textRender()
        }
    })
}

//初始化
(function () {
    bottomRender()
    textRender()
})()
